package com.example.arithmeticleetcode.learnArithmetic.set;

import com.example.arithmeticleetcode.learnArithmetic.set.list.LinkedList;
import com.example.arithmeticleetcode.learnArithmetic.set.list.List;

/**
 * @program: arithmetic-leetcode
 * @description:
 * @author: FangZhen
 * @create: 2020-10-20 16:38
 **/
public class ListSet<E> implements Set<E> {

    //搜索 添加  删除  O(n)
    private List<E> list = new LinkedList<>();

    @Override
    public int size() {
        return list.size();
    }

    @Override
    public boolean isEmpty() {
        return list.isEmpty();
    }

    @Override
    public void clear() {
        list.clear();
    }

    @Override
    public boolean contains(E element) {
        return list.contains(element);
    }

    @Override
    public void add(E element) {
//        if (list.contains(element)) return;
//        list.add(element);
        int index = list.indexOf(element);
        if (index != List.ELEMENT_NO_FUND) {
            list.set(index, element);
        } else {
            list.add(element);
        }

    }

    @Override
    public void remove(E element) {
        int index = list.indexOf(element);
        if (index != List.ELEMENT_NO_FUND)
        list.remove(index);
    }

    @Override
    public void tranversal(Visitor<E> visitor) {
        if (visitor == null) return;
        for (int i = 0, len = list.size(); i < len; i++) {
            if (visitor.visit(list.get(i))) return;
        }
    }
}
